package com.maixun.lib_choosefile.ui

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.tabs.TabLayoutMediator
import com.maixun.lib_choosefile.LocalFileConst
import com.maixun.lib_choosefile.R
import com.maixun.lib_choosefile.adapter.PagerAdapter
import com.maixun.lib_choosefile.entity.LocalFileIm
import kotlinx.android.synthetic.main.local_file_activity_local_file.*
import java.util.*

/**
 * @author：Lmoumou
 * @date：2020/9/30
 */
class LocalFileActivity : AppCompatActivity() {

    private val titleArray by lazy { arrayOf("视频", "音频", "图片", "文档", "其他") }

    private val fragmentList by lazy {
        mutableListOf(
            LocalFileFragment.newInstance(LocalFileConst.VIDEO),
            LocalFileFragment.newInstance(LocalFileConst.AUDIO),
            LocalFileFragment.newInstance(LocalFileConst.IMAGE),
            LocalFileFragment.newInstance(LocalFileConst.DOCUMENT),
            LocalFileFragment.newInstance(LocalFileConst.OTHER)
        )
    }

    private val pagerAdapter by lazy { PagerAdapter(this, fragmentList) }

    val maxNum by lazy { intent.getIntExtra(LocalFileConst.MAX_NUM, 9) }

    private val selectDataList by lazy { ArrayList<LocalFileIm>() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.local_file_activity_local_file)

        tvSend.setOnClickListener {
            setResult(Activity.RESULT_OK, Intent().apply {
                putParcelableArrayListExtra(LocalFileConst.EXTRA_RESULT_SELECTION, selectDataList)
            })
            finish()
        }

        initToolbar()

        initViewPage()

    }

    private fun initViewPage() {
        mViewPager.adapter = pagerAdapter
        mViewPager.adapter = pagerAdapter
        mViewPager.offscreenPageLimit = titleArray.size
        TabLayoutMediator(mTabLayout, mViewPager,
            TabLayoutMediator.TabConfigurationStrategy { tab, position ->
                tab.text = titleArray[position]
            }).attach()
    }

    private fun initToolbar() {
        mToolbar.title = ""
        setSupportActionBar(mToolbar)
        supportActionBar?.apply {
            setHomeButtonEnabled(true)
            setDisplayHomeAsUpEnabled(true)
        }
        mToolbar.setNavigationOnClickListener {
            onBackPressed()
        }

        tvRight.setOnClickListener {
            onBackPressed()
        }
    }

    fun canSelect(): Boolean {
        return selectDataList.size < maxNum
    }

    fun dealWithItem(item: LocalFileIm) {
        if (item.isSelect) {
            selectDataList.add(item)
        } else {
            selectDataList.remove(item)
        }
        tvTitle.text = if (selectDataList.isEmpty()) "选择文件" else "已选${selectDataList.size}个"
    }
}